import java.nio.channels.Pipe;
import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/8 15:35
 * @description 排序 + 双指针
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {3, 1, 4, 1, 5};
        solution.findPairs(nums, 2);
    }
    public int findPairs(int[] nums, int k) {
        Arrays.sort(nums);
        int n = nums.length;
        int l = n-2, r = n-1;
        Set<Pair> set = new HashSet<>();
        while (r >= 0 && l >= 0) {
            while (nums[r] - nums[l] > k) {
                r--;
            }
            if (r != l && nums[r] - nums[l] ==  k) {
                set.add(new Pair(nums[r], nums[l]));
            }
            l--;
        }
        return set.size();
    }
    class Pair{
        Integer a;
        Integer b;
        public Pair(Integer a, Integer b) {
            this.a = a;
            this.b = b;
        }
        @Override
        public int hashCode() {
            return a.hashCode() * b.hashCode();
        }


        @Override
        public boolean equals(Object object) {
            if (object == null) {
                return false;
            }
            if (this == object) {
                return true;
            }
            Pair pair = (Pair) object;
            return pair.a.equals(this.a) && pair.b.equals(this.b);
        }
    }
}
